Component({
  properties: {
    current: {
      type: Number,
      value: 0
    },
    swiperList: {
      type: Array,
      value: []
    },
    duration: {
      type: Number,
      value: 500
    },
    //是否等高
    equalHeight: {
      type: Boolean,
      value: true
    }
  },
  data: {
    swiperHeight: 0,
    currentIndex: 0
  },
  lifetimes: {
    attached() {
      this._initSwiper()
    }
  },
  methods: {

    swiperChange(e) {
      this.setData({
        currentIndex: e.detail.current
      })
    },

    _initSwiper() {
      this._getSwiperInfo('.swiper').then(res => {
        const swiperWidth = Math.floor(res[0].width)
        this.setData({ swiperWidth })
        this._loadImages(swiperWidth).then(res => {
          const { swiperList } = this.data
          const swiperListWithSize = swiperList.map((item, index) => {
            return { ...item, ...res[index] }
          })
          this.setData({ imgSizes: res, swiperListWithSize })
          if (this.data.equalHeight) {
            const maxHeight = this._getMaxHeight(res)
            this.setData({ swiperHeight: maxHeight })
          } else {
            this.setData({ swiperHeight: res[0].height })
          }
        })
      })
    },

    /**
     * 获取swiper信息
     * @param {String} selector 选择器
     */
    _getSwiperInfo(selector) {
      return new Promise(reslove => {
        this.createSelectorQuery()
          .select(selector)
          .boundingClientRect()
          .exec(res => {
            reslove(res)
          })
      })
    },

    /**
     * 批量加载图片(根据swiper宽度等比例缩放)
     * @param {Number} swiperWidth swiper的宽度
     */
    _loadImages(swiperWidth) {
      let count = 0, imgSizes = [];
      const { swiperList } = this.data
      wx.showLoading({
        title: '加载中...',
      })
      return new Promise(reslove => {
        swiperList.forEach((item, index) => {
          wx.getImageInfo({
            src: item.url,
            success(res) {
              const { width, height } = res
              const realHeight = Math.floor(swiperWidth * (height / width))
              imgSizes.push({ id: index, width: swiperWidth, height: realHeight })
            },
            fail(err) {
              console.error(item.url + ' ' + err.errMsg);
            },
            complete() {
              count++
              if (count === swiperList.length) {
                wx.hideLoading()
                const sortedImgSizes = imgSizes.sort((a, b) => {
                  return a.id - b.id > 0 ? 1 : -1
                })
                reslove(sortedImgSizes)
              }
            }
          })
        })
      })
    },

    /**
     * 获取最大高度
     * @param {Array} array 包含高度的数组
     */
    _getMaxHeight(array) {
      let max = array[0].height
      for (let index = 1; index < array.length; index++) {
        const item = array[index];
        if (item.height > max) {
          max = item.height
        }
      }
      return max
    }

  }
})
